package com.ma.Utils;

import com.ma.entity.Files;
import com.ma.server.FilesServer;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @ProjectName: project
 * @Package: com.ma.Utils
 * @ClassName: filesUtil
 * @Author: YHHHH
 * @Description: 文件工具类
 * @Date: 2021/4/2 15:29
 * @Version: 1.0
 */
@Component
public class filesUtil {

    @Autowired
    private FilesServer filesServer;

    public String filesOpe(Integer id, HttpServletResponse response,Integer downOrInline) throws IOException {
        Files byId = filesServer.findById(id);
        String url = byId.getUrl();
        String name = byId.getFilesName() +"."+ byId.getType();
        FileInputStream fis = new FileInputStream(new File(url,name));
        ServletOutputStream os = response.getOutputStream();
        if (downOrInline==1) {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
        }
        if (downOrInline==2){
            response.setHeader("content-disposition", "inline;filename=" + URLEncoder.encode(name, "UTF-8"));
        }
        //文件拷贝
        IOUtils.copy(fis,os);
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
        Integer integer = filesServer.updateDownTime(id);   //更新下载次数
        if (integer!=0){
            return "success";
        }else
        {
            return null;
        }
    }

    /*
    文件删除
     */
    public String filesDelete(Integer id){
        Files byId = filesServer.findById(id);
        String url = byId.getUrl();
        String name = byId.getFilesName() +"."+ byId.getType();
        File file=new File(url,name);
        if(file.exists()&&file.isFile())
            file.delete();
        return null;
    }

}
